<template>
  <div>
    <el-upload :before-upload="beforeUpload" :http-request="httpRequest" :on-change="onChange" :on-remove="onRmove" :class="{hideplus: imgLen}" :limit="limit" :file-list="fileList" :on-preview="onPreview" list-type="picture-card" action="">
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 图片预览弹窗 -->
    <el-dialog width="600px" top="8vh" title="预览" :visible.sync="dialogVisible">
      <img v-if="currentImg" :src="currentImg.url" alt="" style="width:100%;">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
const cos = new COS({
  SecretId: 'AKID0ueBXgffXTGtMemhXFzZw50jlncCXfbO', // 身份识别 ID
  SecretKey: 'e4GDvOcfXBdrtlTyHOKK7i7KSO7g182m' // 身份密钥
})

export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    },
    defaultImg: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      fileList: [{ url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }],
      currentImg: '',
      dialogVisible: false,
    }
  },
  computed: {
    imgLen () {
      return this.fileList.length >= this.limit
    }
  },
  watch: {
    defaultImg (img) {
      this.fileList = [{
        url: img
      }]
    }
  },
  methods: {
    // 上传前的检测工作
    beforeUpload ({ size, type }) {
      const types = ['image/png', 'image/jpeg', 'image/gif']
      if (size / 1024 / 1024 > 1) {
        this.$message.warning('图片太TM大了,老子弄不了')
        return false
      }
      if (!types.includes(type)) {
        this.$message.warning('没见过这种格式的')
        return false
      }
      return true
    },
    // 文件状态改变时 更新fileList状态
    onChange (file, fileList) {
      this.fileList = fileList
    },
    // 添加自定义上传动作
    httpRequest ({ file }) {
      console.log(file);
      if (file) {
        // 执行上传操作
        cos.putObject({
          Bucket: 'yyds-1309192725', /* 存储桶名称 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式（默认即可）
          Body: file, // 上传文件对象
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          console.log(err || data)
          if (err) {
            return this.$message.error('上传图片失败')
          }
          const imgInfo = this.fileList.find(item => {
            return item.uid === file.uid
          })
          imgInfo.status = 'success'
          imgInfo.url = 'https://' + data.Location
        })
      }
    },
    // 监听图片删除操作
    onRmove (file, fileList) {
      // file表示当前删除的图片信息
      // fileList表示删除之后剩余的图片信息
      this.fileList = fileList
    },
    // 获取图片预览信息
    onPreview (file) {
      this.currentImg = file
      this.dialogVisible = true
    },
  }
}
</script>

<style scoped lang="scss">
.hideplus {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
